<template>
  <div id="myLogin">
    <el-dialog
      title="登录"
      width="300px"
      center
      :visible.sync="isLogin"
      :before-close="handleClose"
    >
      <el-form
        :model="LoginUser"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="name">
          <el-input
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="LoginUser.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="LoginUser.password"
            @keyup.enter.native="Login"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            size="medium"
            type="primary"
            @click="Login"
            style="width: 100%"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  name: "MyLogin",
  data() {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };

    return {
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
      },
      LoginUser: {
        username: "",
        password: "",
      },
    };
  },
  created() {},
  methods: {
    ...mapActions(["setUser", "setShowLogin"]),
    ...mapActions({
      setShoppingCart: {
        type: "cart/setShoppingCart",
        // payload: null,
      },
    }),
    handleClose(done) {
      this.isLogin = false;
      done();
    },
    Login() {
      this.$refs["ruleForm"].validate((valid) => {
        //如果通过校验开始登录
        if (valid) {
          this.$axios.get("http://10.41.9.94:8888/users").then((res) => {
            let userList = res.data;
            // console.log(userList);
            let flag = userList.some((item) => {
              return (
                item.username == this.LoginUser.username &&
                item.password == this.LoginUser.password
              );
            });
            let user = userList.find((item) => {
              return (
                item.username == this.LoginUser.username &&
                item.password == this.LoginUser.password
              );
            });
            if (flag) {
              this.$notify({
                title: "成功",
                message: "登录成功",
                type: "success",
                duration: "1500",
              });
              sessionStorage.setItem("user", JSON.stringify(user));
              this.setUser(this.LoginUser);
              this.isLogin = false;
              this.setShoppingCart();
            } else {
              this.$notify({
                title: "失败",
                message: "用户名或者密码错误",
                type: "error",
                duration: "1500",
              });
              this.LoginUser.username = "";
              this.LoginUser.password = "";
            }
          });
        }
      });
    },
  },

  computed: {
    // 获取vuex中的showLogin，控制登录组件是否显示
    isLogin: {
      get() {
        return this.$store.getters.getShowLogin;
      },
      set(val) {
        this.$refs["ruleForm"].resetFields();
        this.setShowLogin(val);
      },
    },
  },
};
</script>
<style lang="scss" scoped></style>
